import {CloseCircleOutlined} from '@ant-design/icons';
import type {ProColumnType} from '@ant-design/pro-components';
import {
    EditableProTable,
    FooterToolbar,
    PageContainer,
    ProForm,
    ProFormText,
    ProFormTextArea,
    ProFormDigit, ProFormSelect,
} from '@ant-design/pro-components';
import {Card, Col, Form, InputNumber, message, Popover, Row} from 'antd';
import type {FC} from 'react';
import React, {useState, useEffect} from 'react';
import useStyles from './style.style';
import {Link, useParams, useNavigate} from 'react-router-dom';
import {hostComputerEdit, hostComputerDetail} from "@/pages/power/host-computer/edit/service";
import {HostComputerListItem} from "@/pages/power/host-computer/list/data";
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {skuSelectList} from "@/pages/power/sku/sku-list/service";

interface TableFormDateType {
    key: string;
    workId?: string;
    name?: string;
    department?: string;
    isNew?: boolean;
    editable?: boolean;
}

type InternalNamePath = (string | number)[];
const fieldLabels = {
    hostComputerId: '主机ID',
    name: '主机名称',
    dataCenterId: '资源池',
    skuId: '规格',
    machineRoomNo: '机房编号', // 机房编号
    cabinetNo: '机柜编号', // 机柜编号
    UPosition: 'U位区间', // U位区间
    hostIp: '主机IP',
    ipoibIp: 'IPoIB IP',
    deviceType: '设备类型',
    systemOS: '系统',
    powerConsumption: '功率',
    loginName: '管理账号',
    loginPassword: '管理密码',
    ipmiIp: 'IPMI IP',
    ipmiIpLoginName: 'IPMI账号',
    ipmiIpLoginPassword: 'IPMI密码',
};

interface ErrorField {
    name: InternalNamePath;
    errors: string[];
}

const SkuEditForm: FC<Record<string, any>> = () => {
    const navigate = useNavigate();
    const params: Record<string, any> = useParams();
    const {styles} = useStyles();
    const [error, setError] = useState<ErrorField[]>([]);
    const getErrorInfo = (errors: ErrorField[]) => {
        const errorCount = errors.filter((item) => item.errors.length > 0).length;
        if (!errors || errorCount === 0) {
            return null;
        }
        const scrollToField = (fieldKey: string) => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
        const errorList = errors.map((err) => {
            if (!err || err.errors.length === 0) {
                return null;
            }
            const key = err.name[0] as 'name' | 'url' | 'owner' | 'approver' | 'dateRange' | 'type';
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <CloseCircleOutlined className={styles.errorIcon}/>
                    <div className={styles.errorMessage}>{err.errors[0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
        <Popover
            title="表单校验信息"
            content={errorList}
            overlayClassName={styles.errorPopover}
            trigger="click"
            getPopupContainer={(trigger: HTMLElement) => {
                if (trigger && trigger.parentNode) {
                    return trigger.parentNode as HTMLElement;
                }
                return trigger;
            }}
        >
          <CloseCircleOutlined/>
        </Popover>
                {errorCount}
      </span>
        );
    };
    const [initialValues, setInitialValues] = useState<HostComputerListItem>();
    const [loading, setLoading] = useState(true);
    const onFinish = async (values: Record<string, any>) => {
        setError([]);
        try {
            values['hostComputerId'] = initialValues?.hostComputerId
            await hostComputerEdit(values);
            message.success('保存成功');
            navigate('/power/host-computer/list');
        } catch {
            // console.log
        }
    };
    const onFinishFailed = (errorInfo: any) => {
        setError(errorInfo.errorFields);
    };
    useEffect(() => {
        const fetchFormData = async () => {
            try {
                const response = await hostComputerDetail({hostComputerId: params?.id});
                setInitialValues(response.data);
            } catch (error) {
                console.error('Error fetching form data:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchFormData();
    }, [params?.id]);

    console.log('initialValues hahahaha:', initialValues);
    return (
        <div>
            {loading ? (
                <div>Loading...</div>
            ) : (
                <ProForm
                    layout="vertical"
                    submitter={{
                        render: (props, dom) => {
                            return (
                                <FooterToolbar>
                                    {getErrorInfo(error)}
                                    {dom}
                                </FooterToolbar>
                            );
                        },
                    }}
                    initialValues={{
                        dataCenterId: initialValues?.dataCenterId,
                        machineRoomNo: initialValues?.machineRoomNo,
                        cabinetNo: initialValues?.cabinetNo,
                        uPositionStart: initialValues?.uPositionStart,
                        uPositionEnd: initialValues?.uPositionEnd,
                        name: initialValues?.name,
                        skuId: initialValues?.skuId,
                        hostIp: initialValues?.hostIp,
                        ipmiIp: initialValues?.ipmiIp,
                        ipoibIp: initialValues?.ipoibIp,
                        deviceType: initialValues?.deviceType,
                        systemOS: initialValues?.systemOS,
                        loginName: initialValues?.loginName,
                        loginPassword: initialValues?.loginPassword,
                        ipmiIpLoginName: initialValues?.ipmiIpLoginName,
                        ipmiIpLoginPassword: initialValues?.ipmiIpLoginPassword,
                        powerConsumption: initialValues?.powerConsumption
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <PageContainer>
                        <Card title="基础信息" className={styles.card} bordered={false}>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.name}
                                        name="name"
                                        fieldProps={{disabled: true}}
                                    />
                                </Col>
                            </Row>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormSelect
                                        label={fieldLabels.dataCenterId}
                                        name="dataCenterId"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请选择资源池',
                                            },
                                        ]}
                                        placeholder="请选择资源池"
                                        request={async () => {
                                            const res = await dataCenterSelectList({});
                                            return res.data.map((item) => ({
                                                label: item.name,
                                                value: item.dataCenterId,
                                            }));
                                        }}
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormSelect
                                        label={fieldLabels.skuId}
                                        name="skuId"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请选择规格',
                                            },
                                        ]}
                                        request={async () => {
                                            const res = await skuSelectList({});
                                            return res.data.map((item) => ({
                                                label: item.skuName,
                                                value: item.skuId,
                                            }));
                                        }}
                                        placeholder="请选择规格"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 6,
                                    }}
                                    md={{
                                        span: 24,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.deviceType}
                                        name="deviceType"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入设备类型信息',
                                            },
                                        ]}
                                        placeholder="请输入设备类型信息"
                                    />
                                </Col>
                            </Row>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.machineRoomNo}
                                        name="machineRoomNo"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入信息',
                                            },
                                        ]}
                                        placeholder="请输入信息"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.cabinetNo}
                                        name="cabinetNo"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入信息',
                                            },
                                        ]}
                                        placeholder="请输入信息"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 6,
                                    }}
                                    md={{
                                        span: 24,
                                    }}
                                    sm={24}
                                >
                                    <Form.Item label={fieldLabels.UPosition} style={{marginBottom: 0}}>
                                        <Form.Item
                                            name="uPositionStart"
                                            rules={[{required: true}]}
                                            style={{display: 'inline-block', width: 'calc(40% - 8px)'}}
                                        >
                                            <InputNumber addonAfter="U" placeholder="开始区间"/>
                                        </Form.Item>
                                        -
                                        <Form.Item
                                            name="uPositionEnd"
                                            rules={[{required: true}]}
                                            style={{display: 'inline-block', width: 'calc(40% - 8px)', margin: '0 8px'}}
                                        >
                                            <InputNumber addonAfter="U" placeholder="结束区间"/>
                                        </Form.Item>
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.systemOS}
                                        name="systemOS"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入系统信息',
                                            },
                                        ]}
                                        placeholder="请输入系统信息"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormDigit
                                        label={fieldLabels.powerConsumption}
                                        name="powerConsumption"
                                        fieldProps={{
                                            addonAfter: "W",
                                            precision: 0
                                        }}
                                        placeholder="请输入功耗信息"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 6,
                                    }}
                                    md={{
                                        span: 24,
                                    }}
                                    sm={24}
                                >

                                </Col>
                            </Row>
                        </Card>
                        <Card title="连接信息" className={styles.card} bordered={false}>
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.hostIp}
                                        name="hostIp"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入主机IP',
                                            },
                                        ]}
                                        placeholder="请输入主机IP"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.loginName}
                                        name="loginName"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入管理账号',
                                            },
                                        ]}
                                        placeholder="请输入管理账号"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 6,
                                    }}
                                    md={{
                                        span: 24,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.loginPassword}
                                        name="loginPassword"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入管理密码',
                                            },
                                        ]}
                                        placeholder="请输入管理密码"
                                    />
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.ipmiIp}
                                        name="ipmiIp"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入',
                                            },
                                        ]}
                                        placeholder="请输入"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.ipmiIpLoginName}
                                        name="ipmiIpLoginName"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入信息',
                                            },
                                        ]}
                                        placeholder="请输入信息"
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.ipmiIpLoginPassword}
                                        name="ipmiIpLoginPassword"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入信息',
                                            },
                                        ]}
                                        placeholder="请输入信息"
                                    />
                                </Col>
                            </Row>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.ipoibIp}
                                        name="ipoibIp"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入信息',
                                            },
                                        ]}
                                        placeholder="请输入信息"
                                    />
                                </Col>
                            </Row>
                        </Card>
                    </PageContainer>
                </ProForm>
            )}
        </div>
    );
};
export default SkuEditForm;
